package com.project.demo.controller;

import com.project.demo.controller.base.BaseController;
import com.project.demo.dao.UserAnswerMapper;
import com.project.demo.dao.UserMapper;
import com.project.demo.entity.User;
import com.project.demo.entity.UserAnswer;
import com.project.demo.service.UserAnswerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户答题
 *
 */
@Slf4j
@RestController
@RequestMapping("user_answer")
public class UserAnswerController extends BaseController<UserAnswer, UserAnswerService> {
    /**
     * 服务对象
     */
    @Autowired
    public UserAnswerController(UserAnswerService service) {
        setService(service);
    }

    @Autowired
    public UserMapper userMapper;

    @Autowired
    public UserAnswerMapper userAnswerMapper;

    @PostMapping("/setScore")
    public Map<String, Integer> setScore(@RequestParam("user_answer_id") Integer userAnswerId, @RequestBody UserAnswer userAnswer, HttpServletRequest request) {
        log.info("userId:{}", userAnswerId);
        log.info(userAnswer.toString());
        HashMap<String, Integer> map = new HashMap<>();
        UserAnswer userAnswerResult = service.selectByUserAnswerId(userAnswerId);
        if ( userAnswer.getScore() >= 100) {
            log.info("开始执行增加积分的代码！");
            Date date = new Date();
            userAnswer.setUpdateTime(null);
            service.save(userAnswer);

            Map<String, String> query = new HashMap<>();
            query.put("user_id", String.valueOf(userAnswerResult.getUser_id()));
            User user = userMapper.selectUserById(userAnswerResult.getUser_id());
            user.setScore(user.getScore() + 2);
            userMapper.updateUser(user);
            map.put("result", 1);
        } else {
            userAnswerMapper.updateById(userAnswer);
            map.put("result", 1);
        }
        return map;

    }
}


